<script setup>
  import { ref, onMounted } from 'vue'
  import taskApi from '@/apis/task.js'

  // 1. 定义响应式数据
  const pickUpList = ref([])
  const nextPage = ref(1) //下一页
  const pages = ref(2) //总页数
  const isTriggered = ref(false) //默认是未触发下拉刷新的状态

  // 2. 定义方法操作响应式数据
  async function getpickUpList(page = 1, pageSize = 5) {
    // 获取服务器数据
    let { data } = await taskApi.list(1, page, pageSize)
    // 赋值给响应式变量
    // 下拉刷新：将第一页数据覆盖pickUpList.value
    if (page === 1) pickUpList.value = []
    // 上拉分页时：将新页的数据追加到前面数据中
    pickUpList.value = [...pickUpList.value, ...data.items]
    // console.log(data.items)
    nextPage.value = ++data.page //拿到下一页
    pages.value = data.pages //总页数
  }

  onMounted(() => {
    // 页面加载后就发请求获取数据
    getpickUpList()
  })

  // 定义上拉分页的触底函数
  function onScrollToLower() {
    // 1. 判断，如果nextPage.value大于pages.value则直接不执行代码
    if (nextPage.value > pages.value) {
      return uni.utils.toast('已经没有数据')
    }
    // 2. 重新调用getpickUpList方法，传入nextPage的值即可
    getpickUpList(nextPage.value)
  }

  // 定义下拉刷新的回调函数
  async function onRefresher() {
    // 1. 打开下拉刷新的动画图
    isTriggered.value = true
    // 2. 请求第一页数据
    const cpage = 1
    await getpickUpList(cpage)
    // 3. 关闭下拉刷新的动画图
    isTriggered.value = false
  }
</script>

<template>
  <scroll-view
    scroll-y
    refresher-enabled
    :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresher"
    @scrolltolower="onScrollToLower"
    class="scroll-view"
  >
    <view class="scroll-view-wrapper">
      <view v-for="pickup in pickUpList" :key="pickup.id" class="task-card">
        <navigator
          hover-class="none"
          :url="`/subpkg_task/detail/index?id=${pickup.id}`"
        >
          <view class="header">
            <text class="no">任务编号: {{ pickup.transportTaskId }}</text>
            <!-- <text class="status">已延迟</text> -->
          </view>
          <view class="body">
            <view class="timeline">
              <view class="line">{{ pickup.startAddress }}</view>
              <view class="line">{{ pickup.endAddress }}</view>
            </view>
          </view>
        </navigator>
        <view class="footer">
          <view class="label">提货时间</view>
          <view class="time">{{ pickup.planDepartureTime }}</view>
          <navigator
            v-if="pickup.enablePickUp"
            hover-class="none"
            :url="`/subpkg_task/pickup/index?id=${pickup.id}`"
            class="action"
            >提货</navigator
          >
          <button
            v-if="!pickup.enablePickUp"
            class="action"
            style="color: white"
            disabled="true"
          >
            提货
          </button>
        </view>
      </view>

      <view v-if="false" class="task-blank">无待提货物</view>
    </view>
  </scroll-view>
</template>

<style lang="scss" scoped>
  @import './styles.scss';
</style>
